package com.laxia.util;

import com.alibaba.excel.EasyExcel;
import com.laxia.exception.ExceptionFactory;
import com.laxia.exception.ensure.Ensure;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @author weishuai
 * @since 2019-10-28
 */
@Slf4j
public class ExcelUtil {

    public static <T> void download(String fileName, List<T> data) {
        Ensure.that(data).isNotEmpty("未查询到有效数据");
        try {
            HttpServletResponse response = SessionUtil.getCurrentResponse();
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里防止中文乱码
            fileName = StringUtil.encode(fileName);
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), data.get(0).getClass()).sheet("sheet1").doWrite(data);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw ExceptionFactory.create("下载出错!");
        }
    }
}
